<template>  
  <div class="signature-pad">  
    <canvas  
      ref="canvasRef"  
      @mousedown="startDrawing"  
      @mouseup="stopDrawing"  
      @mousemove="draw"  
      @mouseout="stopDrawing"  
      :width="width"  
      :height="height"  
      style="border: 1px solid #ccc; cursor: crosshair;"  
    ></canvas>  
    <a-button type="primary" @click="clearCanvas" preIcon="ant-design:delete-outlined"> 清除</a-button>
    <a-button type="primary" @click="saveAndUpload" preIcon="ant-design:plus-outlined"> 保存并上传</a-button>
  </div>  
</template>

<script lang="ts">  
import { defineComponent, ref, onMounted } from 'vue';  
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
  
export default defineComponent({  
  name: 'SignaturePad',  
  props: {  
    width: {  
      type: Number,  
      default: 800,  
    },  
    height: {  
      type: Number,  
      default: 400,  
    },  
    uploadUrl: {  
      type: String,  
      required: true, // 假设你需要一个上传URL  
    },  
  },  
  emits: ['ok'],
  setup(props, { expose,emit }) {  
    const canvasRef = ref<HTMLCanvasElement | null>(null);  
    let ctx: CanvasRenderingContext2D | null = null;  
    let isDrawing = false;  
    let lastX = 0;  
    let lastY = 0;
    const { createMessage, createWarningModal } = useMessage();
  
    onMounted(() => {  
      if (canvasRef.value) {  
        ctx = canvasRef.value.getContext('2d');  
        canvasRef.value.width = props.width;  
        canvasRef.value.height = props.height;  
      }  
    });  
  
    function startPosition(e: MouseEvent) {  
      const rect = canvasRef.value!.getBoundingClientRect();  
      lastX = e.clientX - rect.left;  
      lastY = e.clientY - rect.top;  
    }  
  
    function draw(e: MouseEvent) {  
      if (!isDrawing || !ctx) return;  
      ctx.beginPath();  
      ctx.moveTo(lastX, lastY);  
      const rect = canvasRef.value!.getBoundingClientRect();  
      ctx.lineTo(e.clientX - rect.left, e.clientY - rect.top);  
      ctx.strokeStyle = '#000000';  
      ctx.lineWidth = 2;  
      ctx.lineCap = 'round';  
      ctx.stroke();  
      lastX = e.clientX - rect.left;  
      lastY = e.clientY - rect.top;  
    }  
    
    function startDrawing(e: MouseEvent) {  
      isDrawing = true;  
      startPosition(e);  
      draw(e);  
    }  
  
    function stopDrawing(e?: MouseEvent) {  
      isDrawing = false;  
      if (e) {  
        draw(e); // Optionally draw the last point  
      }  
    }  
  
    function clearCanvas() {  
      if (ctx) {  
        ctx.clearRect(0, 0, canvasRef.value!.width, canvasRef.value!.height);  
      }  
    }  
    
    function canvasToBlobPromise(canvas, type = 'image/png', quality = 1.0) {  
      return new Promise((resolve, reject) => {  
        try {  
          canvas.toBlob((blob) => {  
            if (!blob) {  
              reject(new Error('Failed to generate blob'));  
            } else {  
              resolve(blob);  
            }  
          }, type, quality);  
        } catch (error) {  
          reject(error);  
        }  
      });  
    }  
      
    // 在你的 saveAndUpload 方法中使用它  
    function saveAndUpload() {  
      if (!ctx || !canvasRef.value) return;  
      
      canvasRef.value.toBlob((blob) => {  
        if (!blob) return;  

        //TODO 请求怎样处理的问题
        let headers = {
          'Content-Type': 'multipart/form-data',
        };

        console.log('Upload success----------------:', blob);
        const formData = new FormData();  
        formData.append('biz', "temp");
        formData.append("file", blob,"signature.png");
        defHttp.post({url:"/sys/common/upload",params: formData, headers }, { isTransformResponse: false }).then(res => {
          console.log("====reponse========="+JSON.stringify(res))
          if (res.success) {
            createMessage.success("上传成功!");
            emit('ok',res.message);
            //上传成功之后清空组件内容
            clearCanvas();
          } else {
            createMessage.warning(res.message);
          }
        });
      }, 'image/png');  
    }
  
    // 如果你想将方法暴露给模板外的父组件，可以使用 expose  
    // expose({ handleMouseDown, handleMouseUp, handleMouseMove });  
  
    return {  
      canvasRef,  
      startDrawing,  
      stopDrawing,  
      draw,  
      clearCanvas,  
      saveAndUpload,  
    };  
  },  
});  
</script>  

<style scoped>  
.signature-pad canvas {  
  display: block; /* 去除canvas下方的空白 */  
}  
</style>
